<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <h3>基本信息</h3>
      </div>
      <div class="info-img">
        <el-image :src="form.headImg" class="portrait"/>
        <div class="info-num-item">
          <p>{{ form.works }}</p>
          <p class="title">作品</p>
        </div>
        <div class="info-num-item">
          <p>{{ form.follows }}</p>
          <p class="title">关注</p>
        </div>
        <div class="info-num-item">
          <p>{{ form.fans }}</p>
          <p class="title">粉丝</p>
        </div>
        <div class="info-num-item">
          <p>{{ form.likes }}</p>
          <p class="title">获赞</p>
        </div>
        <div class="info-num-item">
          <p>{{ form.collects }}</p>
          <p class="title">收藏</p>
        </div>
      </div>
      <div class="info-detail p-t-15">
        <div>
          <p>
            <span class="label">会员昵称：</span>
            <span>{{ form.nickName }}</span>
          </p>
          <p>
            <span class="label">账号状态：</span>
            <span>{{ riskStatusMap[riskForm.riskStatus] }}</span>
          </p>
          <p>
            <span class="label">手机号码：</span>
            <span>{{ form.mobile }}</span>
          </p>
          <p>
            <span class="label">注册时间：</span>
            <span>{{ form.registerTime }}</span>
          </p>
          <p>
            <span class="label">最近活跃时间：</span>
            <span>{{ form.lastUseTime }}</span>
          </p>
          <p>
            <span class="label">用户类型：</span>
            <span>{{ memberTypeMap[form.memberType] }}</span>
          </p>
          <p>
            <span class="label">自媒体类型：</span>
            <span>{{ mediaTypeMap[form.mediaType] }}</span>
          </p>
          <p>
            <span class="label">一个月内是否双开：</span>
            <span>{{ form.manyOpen ? '是' : '否' }}</span>
          </p>
          <p>
            <span class="label">一个月内是否使用模拟器：</span>
            <span>{{ form.simular ? '是' : '否' }}</span>
          </p>
          <p>
            <span class="label">一个月内App使用总时长：</span>
            <span>{{ riskForm.appUseTime }} min</span>
          </p>
          <p>
            <span class="label">一个月内使用app次数：</span>
            <span>{{ riskForm.appUseCount }}</span>
          </p>
          <p>
            <span class="label">一周内内容浏览量：</span>
            <span>{{ form.views }}</span>
          </p>
        </div>

        <div class="cross-line"/>

        <div class="m-r-100">
          <p>
            <span class="label">最近使用APP版本：</span>
            <span>{{ form.appVersion }}</span>
          </p>
          <p>
            <span class="label">当前推送开启状态：</span>
            <span>{{ form.push == 1 ? '未设置' : form.push == 2 ?  '关闭' : '开启' }}</span>
          </p>
          <p>
            <span class="label">使用设备型号：</span>
            <span>{{ form.deviceModel }}</span>
          </p>
          <p>
            <span class="label">设备系统版本：</span>
            <span>{{ form.systemVersion }}</span>
          </p>
          <p>
            <span class="label">是否使用wifi登录：</span>
            <span>{{ form.wifi ? '是' : '否' }}</span>
          </p>
          <p>
            <span class="label">IP定位：</span>
            <span>{{ form.ipAddress }}</span>
          </p>
          <p>
            <span class="label">设备ID:</span>
            <span>{{ form.deviceId }} ({{ form.deviceIdCount }})</span>
            <el-button class="fr" size="small" type="primary" @click="goUserDetail('?device=' + form.deviceId)"> 详情></el-button>
          </p>
          <p>
            <span class="label">MAC地址：</span>
            <span v-if="!form.mac"> 无 </span>
            <span v-else>{{ form.mac }} ({{ form.macCount }})</span>
            <el-button class="fr" size="small" type="primary" @click="goUserDetail('?mac=' + form.mac)"> 详情></el-button>
          </p>
          <p>
            <span class="label">提现账号：</span>
            <span>{{ form.accountList && form.accountList[0] && form.accountList[0].accountNum || '无' }}</span>
            <el-button class="fr" size="small" type="primary" @click="showWithdrawAccount()"> 详情></el-button>
          </p>
          <p>
            <span class="label">状态变更次数：</span>
            <span>{{ riskForm.statusChangeCount || 0 }}</span>
            <el-button class="fr" size="small" type="primary" @click="checkHistory()"> 详情></el-button>
          </p>
          <p>
            <span class="label">徒弟数量：</span>
            <span >{{ riskForm.childCount }}</span>
            <el-button class="fr" size="small" type="primary" @click="goUserDetail('?masterId=' + memberId + '&childLevel=1')"> 详情></el-button>
          </p>
        </div>
      </div>
    </el-card>

    <el-card class="box-card m-t-20">
      <div slot="header" class="clearfix">
        <h3>风控信息</h3>
      </div>

      <div class="risk p-t-15">
        <div class="risk-item">
          <p>金币</p>
        </div>
        <div class="risk-item">
          <p class="green">{{ riskForm.currentCoin }}</p>
          <p class="title">余额</p>
        </div>
        <div class="risk-item">
          <p class="red">{{ riskForm.expireCoin }}</p>
          <p class="title">过期</p>
        </div>
        <div class="risk-item">
          <p class="black">{{ riskForm.historyCoin }}</p>
          <p class="title">历史
            <el-tooltip content="累计金币总额=金币余额 + 消费的金币数额（=兑换成零钱的数额 + 充值手机的数额 + 金币失效的数额 + 金币兑换的数额（仅兑换类型））" class="item" effect="dark" placement="bottom"><i class="el-icon-warning"/></el-tooltip>
          </p>
        </div>
      </div>

      <div class="p-t-15">
        <el-button :type="active1 == '7' ? 'primary' : ''" @click="changeTime(7, 1)">7天</el-button>
        <el-button :type="active1 == '30' ? 'primary' : ''" @click="changeTime(30, 1)">一个月</el-button>
        <el-button :type="active1 == '90' ? 'primary' : ''" @click="changeTime(90, 1)">三个月</el-button>
        <el-button :type="active1 == '180' ? 'primary' : ''" @click="changeTime(180, 1)">半年</el-button>
        <el-button :type="active1 == 'register' ? 'primary' : ''" @click="changeTime('register', 1)">注册后</el-button>
        <el-date-picker v-model="datePicker1" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" class="w-240"/>
        <el-button type="primary" @click="searchCoin()">搜索</el-button>
      </div>

      <div class="flex">
        <div class="echart" id="one"/>
        <div class="echart" id="one-all"/>
        <div class="table">
          <el-table v-loading="coinDetail.listLoading" :data="coinDetail.list" border size="small">
            <el-table-column prop="createTime" width="140" label="时间" align="center"/>
            <el-table-column prop="nameDefineName" label="类型" align="center"/>
            <el-table-column prop="cashAmount" width="120" label="数额" align="center">
              <template slot-scope="{row}">
                <span> {{ row.coinAmount > 0 ? '+' + row.coinAmount : row.coinAmount}} </span>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" v-if="coinDetail.total>0">
            <el-pagination
            :current-page="coinDetail.index"
            :page-sizes="[20, 30, 50]"
            :page-size="coinDetail.size"
            :total="coinDetail.total"
            layout="total, prev, pager, next"
            @size-change="(val) => handlePageChange(val, 'size', 7, 'coinDetail')"
            @current-change="(val) => handlePageChange(val, 'index', 7, 'coinDetail')"/>
          </div>
        </div>
      </div>

      <div class="risk p-t-15">
        <div class="risk-item">
          <p>零钱</p>
        </div>
        <div class="risk-item">
          <p class="green">{{ riskForm.currentCash }}</p>
          <p class="title">余额</p>
        </div>
        <div class="risk-item">
          <p class="red">{{ riskForm.withdrawalCash }}</p>
          <p class="title">提现成功</p>
        </div>
        <div class="risk-item">
          <p class="black">{{ riskForm.historyCash }}</p>
          <p class="title">历史</p>
        </div>
      </div>

      <div class="p-t-15">
        <el-button :type="active2 == '7' ? 'primary' : ''" @click="changeTime(7, 2)">7天</el-button>
        <el-button :type="active2 == '30' ? 'primary' : ''" @click="changeTime(30, 2)">一个月</el-button>
        <el-button :type="active2 == '90' ? 'primary' : ''" @click="changeTime(90, 2)">三个月</el-button>
        <el-button :type="active2 == '180' ? 'primary' : ''"  @click="changeTime(180, 2)">半年</el-button>
        <el-button :type="active2 == 'register' ? 'primary' : ''"  @click="changeTime('register', 2)">注册后</el-button>
        <el-date-picker v-model="datePicker2" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" class="w-240"/>
        <el-button type="primary" @click="searchCash()">搜索</el-button>
      </div>

      <div class="flex">
        <div class="echart" id="two"/>
        <div class="echart" id="two-all"/>
        <div class="table">
          <el-table v-loading="cashDetail.listLoading" :data="cashDetail.list" border size="small">
            <el-table-column prop="createTime" width="140" label="时间" align="center"/>
            <el-table-column prop="nameDefineName" label="类型" align="center"/>
            <el-table-column prop="cashAmount" width="120" label="数额" align="center">
              <template slot-scope="{row}">
                <span> {{ row.cashAmount > 0 ? '+' + row.cashAmount : row.cashAmount}} </span>
              </template>
            </el-table-column>
          </el-table>

          <div class="block" v-if="cashDetail.total>0">
            <el-pagination
            :current-page="cashDetail.index"
            :page-sizes="[20, 30, 50]"
            :page-size="cashDetail.size"
            :total="cashDetail.total"
            layout="total, prev, pager, next"
            @size-change="(val) => handlePageChange(val, 'size', 8, 'cashDetail')"
            @current-change="(val) => handlePageChange(val, 'index', 8, 'cashDetail')"/>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="box-card m-t-20">
      <div slot="header" class="clearfix">
        <h3>邀请好友任务</h3>
      </div>
      <div class="account">
        <p>
          <span>徒弟多开数量：</span>
          <span class="m-r-10">{{ inviteForm.childManayCount || 0 }}</span>
        </p>
        <p>
          <span>徒弟模拟器数量：</span>
          <span class="m-r-10">{{ inviteForm.childSimulatorCount || 0 }}</span>
        </p>
        <p>
          <span>设备号重复数量:</span>
          <span class="m-r-10">{{ inviteForm.deviceDupCount || 0 }}</span>
        </p>
        <p>
          <span>MAC值重复数量:</span>
          <span class="m-r-10">{{ inviteForm.macDupCount || 0 }}</span>
        </p>
        <p>
          <span>同IP账号数量:</span>
          <span class="m-r-10">{{ inviteForm.ipDupCount || 0 }}</span>
        </p>
        <p :class="{'disabled': !inviteForm.masterId}" class="pointer" @click="goUserDetail('?memberId=' + inviteForm.masterId)">
          <span>师傅会员ID:</span>
          <span class="m-r-10">{{ inviteForm.masterId || '无' }}</span>
          <el-button v-if="inviteForm.masterId" size="small" type="primary"> 详情></el-button>
        </p>
        <p class="pointer" @click="goUserDetail('?masterId=' + memberId + '&childLevel=1')">
          <span>徒弟数量:</span>
          <span class="m-r-10">{{ inviteForm.childCount || 0 }}</span>
          <el-button size="small" type="primary"> 详情></el-button>
        </p>
        <p class="pointer" @click="goUserDetail('?masterId=' + memberId + '&childLevel=5')">
          <span>5层徒弟数量:</span>
          <span class="m-r-10">{{ inviteForm.childCount5Level }}</span>
          <el-button size="small" type="primary"> 详情></el-button>
        </p>
      </div>

      <div class="p-t-15">
        <el-button :type="active3 == '7' ? 'primary' : ''" @click="changeTime(7, 3)">7天</el-button>
        <el-button :type="active3 == '30' ? 'primary' : ''" @click="changeTime(30, 3)">一个月</el-button>
        <el-button :type="active3 == '90' ? 'primary' : ''" @click="changeTime(90, 3)">三个月</el-button>
        <el-button :type="active3 == '180' ? 'primary' : ''" @click="changeTime(180, 3)">半年</el-button>
        <el-button :type="active3 == 'register' ? 'primary' : ''" @click="changeTime('register', 3)">注册后</el-button>
        <el-date-picker v-model="datePicker3" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" class="w-240"/>
        <el-button type="primary" @click="getChildReport()">搜索</el-button>
      </div>

      <div class="flex">
        <div class="echart" id="three"/>
        <div class="table">
          <el-table v-loading="listLoading.child" :data="listData.child" border size="small">
            <el-table-column width="150" label="会员ID" align="center">
              <template slot-scope="{row}">
                <span class="pointer blue" @click="goUserDetail('?memberId=' + row.id)">{{ row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column property="totalCoin" label="金币总额" align="center"/>
            <el-table-column width="150" label="会员状态" align="center">
              <template slot-scope="{row}">
                <span>{{ riskStatusMap[row.status] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <el-card class="box-card m-t-20">
      <div slot="header" class="clearfix">
        <h3>用户访问行为历史记录</h3>
      </div>

      <el-row>
        <el-autocomplete v-model="visitQuery.apiType" :fetch-suggestions="querySearch" placeholder="请输入事件关键词" clearable size="small" class="w-240"/>
        <el-input v-model="visitQuery.content" placeholder="请输入内容关键字" size="small" class="w-180" clearable />
        <el-date-picker v-model="datePicker4" :picker-options="pickerOptions" size="small" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" class="w-240"/>
        <el-select v-model="visitQuery.location" size="small" clearable collapse-tags placeholder="全部城市">
          <el-option
            v-for="item of cityList"
            :key="item"
            :label="item"
            :value="item"/>
        </el-select>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search(4, 'visitQuery')">搜索</el-button>
      </el-row>

      <el-row class="p-t-15">
        <el-table v-loading="listLoading.visit" :data="listData.visit" border size="small" max-height="600">
          <el-table-column property="createTime" width="135" label="日期"/>
          <el-table-column property="apiType" label="事件"/>
          <el-table-column property="content" label="操作内容"/>
          <el-table-column property="uuid" label="UUID"/>
          <el-table-column property="ip" width="120" label="IP地址">
            <template slot-scope="scope">
              <router-link :to="{ path:'/sys_analysis/IPQuery', query: { ip: scope.row.ip }}">{{ scope.row.ip }}</router-link>
            </template>
          </el-table-column>
          <el-table-column property="location" width="150" label="地址"/>
          <el-table-column property="systemVersion" width="100" label="设备系统版本"/>
          <el-table-column property="appVersion" width="100" label="APP版本"/>
          <el-table-column property="deviceNetType" width="120" label="运营商"/>
          <el-table-column property="deviceId" label="设备ID"/>
          <el-table-column property="deviceModel" label="设备型号"/>
        </el-table>
      </el-row>

      <div v-if="total.visit > 0" class="block fr">
        <el-pagination
          :current-page="visitQuery.page"
          :page-sizes="[15, 20, 30]"
          :page-size="visitQuery.size"
          :total="total.visit"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="(val) => handlePageChange(val, 'size', 4, 'visitQuery')"
          @current-change="(val) => handlePageChange(val, 'page', 4, 'visitQuery')"
        />
      </div>
    </el-card>

    <el-card class="box-card m-t-20">
      <div slot="header" class="clearfix">
        <h3>金币红包活动历史记录</h3>
      </div>
      <el-row>
        <el-input v-model="activityQuery.keyword" placeholder="请输入活动关键字" size="small" class="w-180" clearable />
        <el-date-picker v-model="datePicker5" :picker-options="pickerOptions" size="small" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd" class="w-240"/>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search(5, 'activityQuery')">搜索</el-button>
      </el-row>

      <el-row class="p-t-15">
        <el-table v-loading="listLoading.activity" :data="listData.activity" border size="small">
          <el-table-column property="date" width="150" label="日期" align="center"/>
          <el-table-column property="hour" width="200" label="时间段" align="center"/>
          <el-table-column align="center" label="金币活动">
            <template slot-scope="scope" >
              {{ scope.row.content }}
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <div v-if="total.activity > 0" class="block fr">
        <el-pagination
          :current-page="activityQuery.page"
          :page-sizes="[15, 20, 30]"
          :page-size="activityQuery.size"
          :total="total.activity"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="(val) => handlePageChange(val, 'size', 5, 'activityQuery')"
          @current-change="(val) => handlePageChange(val, 'page', 5, 'activityQuery')"
        />
      </div>
    </el-card>

    <el-card class="box-card m-t-20">
      <div slot="header" class="clearfix">
        <h3>阅读任务红包明细</h3>
      </div>
      <el-row>
        <el-select v-model="readQuery.jobType" size="small" clearable>
          <el-option
            v-for="item in jobOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-select v-model="readQuery.readContentType" size="small" clearable>
          <el-option
            v-for="item in readOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <el-input :value="readQuery.newsId" placeholder="请输入内容ID" size="small" class="w-180" clearable @input="value => (readQuery.newsId = value.replace(/[^\d]/g, ''))" />
        <el-date-picker
          v-model="datePicker6"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"/>
        <el-button type="primary" icon="el-icon-search" size="small" @click="search(6, 'readQuery', 'beginTime')">搜索</el-button>
        <el-button type="primary" size="small" @click="toExport()">导出</el-button>
      </el-row>

      <el-row class="p-t-15">
        <el-table v-loading="listLoading.read" :data="listData.read" border size="small" max-height="600">
          <el-table-column property="createTime" width="150" label="奖励时间" align="center"/>
          <el-table-column property="jobType" width="150" label="任务类型" align="center"/>
          <el-table-column property="readContentType" width="150" label="阅读内容类型" align="center"/>
          <el-table-column width="450" label="内容标题" align="center">
            <template slot-scope="{row}">
              <span v-if="row.newsType==5">{{ row.title && row.title.length > 30 ? row.title.slice(0, 30) + '...' : row.title }} </span>
              <span v-if="row.newsType!=5">{{ row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column property="objectId" label="内容ID" align="center"/>
          <el-table-column property="coinAmount" label="奖励金币数" align="center"/>
          <el-table-column property="readTime" label="阅读时长（s）" align="center"/>
          <el-table-column property="todayCount" label="当日同类奖励计数" align="center"/>
        </el-table>
      </el-row>

      <div v-if="total.read > 0" class="block fr">
        <el-pagination
          :current-page="readQuery.page"
          :page-sizes="[15, 20, 30]"
          :page-size="readQuery.size"
          :total="total.read"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="(val) => handlePageChange(val, 'size', 6, 'readQuery')"
          @current-change="(val) => handlePageChange(val, 'page', 6, 'readQuery')"
        />
      </div>
    </el-card>

    <!-- 全部提现账号 -->
    <el-dialog
      :visible.sync="show.withdrawAccount"
      :title="$t('all_withdraw_account')"
    >
      <el-row>
        <label>{{ $t('current_withdraw_account') }}: </label>
        <span>{{ accountList && accountList[0] && accountList[0].accountNum }}</span>
        <span> {{ accountList && accountList[0] && accountList[0].ownerName }} </span>
      </el-row>
      <el-row style="margin: 10px 0">
        <label>{{ $t('history_withdraw_account') }}: </label>
      </el-row>
      <el-table v-if="accountList.length" :data="accountList" border fit>
        <el-table-column
          :label="$t('serial_number')"
          type="index"
          width="60px"
          align="center"
        />
        <el-table-column
          :label="$t('account')"
          property="accountNum"
          align="center"
        />
        <el-table-column
          :label="$t('bind_time')"
          property="createTime"
          align="center"
        />
        <el-table-column
          :label="$t('user_id_ever_bind_phone')"
          property="otherBindUser"
          align="center"
        >
          <template slot-scope="{ row }">
            <span v-if="row.otherBindUser"> {{ row.otherBindUser }} </span>
            <span v-else> {{ $t('none') }} </span>
          </template>
        </el-table-column>
      </el-table>
      <el-row v-else>{{ $t('temporally_none') }}</el-row>
    </el-dialog>

    <!-- 变更历史 -->
    <el-dialog :visible.sync="show.history" title="会员状态变更历史" width="1000px">
      <el-table
        :data="historyData"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="变更时间"
          prop="updateTime"
          align="center"
          width="200"
        />

        <el-table-column
          label="操作人"
          prop="operatorName"
          align="center"
          width="120"
        />

        <el-table-column
          label="变更"
          align="center"
        >
          <template slot-scope="{row}">
            {{ riskStatusMap[row.fromStatus] }} >  {{ riskStatusMap[row.toStatus] }}
          </template>
        </el-table-column>

        <el-table-column
          label="变更理由"
          align="center"
        >

          <template slot-scope="{row}" >
            <span :title="row.allRules">
              {{ row.firstRuleGroupName }} {{ row.ruleGroupNameList.length>1?"...":'' }}
            </span>
          </template>

        </el-table-column>

      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.history = false;"> 关闭 </el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getMemberInfoApi,
  getMemberRiskInfoApi,
  getAcquisitionApi,
  getAllCityApi,
  getApiTypeListApi,
  getApiVisitLogPageApi,
  getMemberActionListApi,
  getReadrecordApi,
  getChangeRecordsApi,
  getRiskInfoCashApi,
  getRiskInfoCoinApi,
  getChildReportApi,
  getRiskInfoCoinDetailApi,
  getRiskInfoCashDetailApi
} from '@/api/user-exception-filtering/user-details';
import { format } from 'date-fns';
import { getMemberList } from '@/api/user-exception-filtering/abnormal-behavior';
import timeUtils from '@/utils/timeHandle.js';
import { getToken } from '@/utils/auth';
import echarts from 'echarts';
import 'echarts/extension/bmap/bmap';

const memberTypeMap = {
  1: '手机注册用户',
  3: '普通用户',
  4: 'Googplus注册用户',
  5: 'Facebook注册用户',
  6: '微信注册用户',
  7: 'QQ注册用户',
  8: 'Twitter用户',
  9: 'Line注册用户',
  10: '后台创建用户',
  11: '手机验证码登陆用户',
  12: '苹果账号登陆'
};

const mediaTypeMap = {
  1: '非自媒体',
  2: '普通自媒体',
  3: '自媒体大V'
};

const riskStatusMap = {
  GREY: '灰名单',
  BLACK: '黑名单',
  NOTSURE: '疑似异常',
  NORMAL: '正常',
  WHITE: '白名单',
  GREYANDBLACK: '黑名单或灰名单'
};

const jobOptions = [
  {
    value: null,
    label: '任务类型'
  },
  {
    value: 1,
    label: '阅读任务'
  },
  {
    value: 2,
    label: '视频播放任务'
  }
];

const readOptions = [
  {
    value: null,
    label: '阅读内容类型'
  },
  {
    value: 1,
    label: '图文阅读'
  },
  {
    value: 2,
    label: '图集阅读'
  },
  {
    value: 3,
    label: '视频播放'
  },
  {
    value: 5,
    label: '微头条推荐列表'
  },
  {
    value: 8,
    label: '小视频播放'
  }
];

const timeMap = {
  7: [
    timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 6, 'date'),
    timeUtils.timeHandle(new Date().getTime(), 'date')
  ],
  30: [
    timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 29, 'date'),
    timeUtils.timeHandle(new Date().getTime(), 'date')
  ],
  90: [
    timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 89, 'date'),
    timeUtils.timeHandle(new Date().getTime(), 'date')
  ],
  180: [
    timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 179, 'date'),
    timeUtils.timeHandle(new Date().getTime(), 'date')
  ]
};

const presetTime = [
  timeUtils.timeHandle(new Date().getTime() - 3600 * 1000 * 24 * 6, 'date'),
  timeUtils.timeHandle(new Date().getTime(), 'date')
];

export default {
  data() {
    return {
      active1: '7',
      active2: '7',
      active3: '7',
      memberTypeMap,
      mediaTypeMap,
      riskStatusMap,
      jobOptions,
      readOptions,
      datePicker1: presetTime, // 风控信息金币兑换
      datePicker2: presetTime, // 风控信息邀请好友
      datePicker3: presetTime, // 邀请好友
      datePicker4: presetTime, // 访问行为
      datePicker5: presetTime, // 金币红包活动历史
      datePicker6: presetTime, // 阅读任务红包
      show: {
        withdrawAccount: false, // 全部提现账号
        history: false // 会员状态变更历史
      },
      memberId: null,
      form: {
        fuck: null
      },
      riskForm: {},
      inviteForm: {},
      pickerMinDate: '',
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.pickerMinDate = minDate.getTime();
          if (maxDate) {
            this.pickerMinDate = '';
          }
        },
        disabledDate: time => time.getTime() > Date.now()
      },
      listLoading: {
        visit: false,
        activity: false,
        read: false,
        child: false
      },
      listData: {
        visit: [],
        activity: [],
        read: [],
        child: []
      },
      total: {
        visit: 0,
        activity: 0,
        read: 0
      },
      visitQuery: {
        apiType: '',
        content: '',
        startTime: `${timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        )}`,
        endTime: `${timeUtils.timeHandle(new Date().getTime(), 'date')}`,
        location: ''
      },
      activityQuery: {
        keyword: '',
        startTime: `${timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        )}`,
        endTime: `${timeUtils.timeHandle(new Date().getTime(), 'date')}`,
        page: 1,
        size: 50
      },
      readQuery: {
        beginTime: `${timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        )} 00:00:00`,
        endTime: `${timeUtils.timeHandle(
          new Date().getTime(),
          'date'
        )} 23:59:59`,
        page: 1,
        size: 20,
        newsId: null,
        jobType: null, // 任务类型
        readContentType: null // 阅读内容类型
      },
      coinDetail: {
        total: 0,
        list: [],
        index: 1,
        size: 10,
        listLoading: false
      },
      cashDetail: {
        total: 0,
        list: [],
        index: 1,
        size: 10,
        listLoading: false
      },
      cityList: [], // 全部城市
      actionOption: [], // 事件关键词
      historyData: [], // 会员状态变更历史
      accountList: [] // 全部提现账号
    };
  },

  created() {
    this.memberId = this.$route.query.memberId;
    this.init();
    this.getAllEvent();
  },

  methods: {
    init() {
      this.getBaseInfo();
      this.getRiskInfo();
      this.getAcquisition();
      this.getVisitLog();
      this.getActionList();
      this.getReadrecord();
      this.searchCoin();
      this.searchCash();
      this.getChildReport();
    },

    // 基本信息
    async getBaseInfo() {
      const { memberId } = this;
      try {
        const { code, data } = await getMemberInfoApi({ memberId });
        if (code == 200) {
          this.form = data || {};
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    // 风控信息
    async getRiskInfo() {
      const { memberId } = this;
      try {
        const { code, data } = await getMemberRiskInfoApi({ memberId });
        if (code == 200) {
          this.riskForm = data || {};
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    // 邀请好友任务汇总
    async getAcquisition() {
      const { memberId } = this;
      try {
        const { code, data } = await getAcquisitionApi({ memberId });
        if (code == 200) {
          this.inviteForm = data || {};
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    // 用户访问行为历史
    async getVisitLog() {
      const { memberId, visitQuery } = this;
      const query = { ...visitQuery, memberId };
      try {
        this.listLoading.visit = true;
        const { code, data, msg } = await getApiVisitLogPageApi(query);
        this.listLoading.visit = false;
        if (code == 200) {
          this.listData.visit = data.list || [];
          this.total.visit = Number(data.total) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading.visit = false;
      }
    },

    // 金币红包活动历史
    async getActionList() {
      const { memberId, activityQuery } = this;
      const query = { ...activityQuery, memberId };
      try {
        this.listLoading.activity = true;
        const { code, data, msg } = await getMemberActionListApi(query);
        this.listLoading.activity = false;
        if (code == 200) {
          this.listData.activity = data.list.map(item => {
            item.content = '';
            item.list.forEach(listItem => {
              item.content += `${listItem.nameDefine}${listItem.count}次; `;
            });
            return item;
          });
          this.total.activity = Number(data.total) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading.activity = false;
      }
    },

    // 阅读任务红包明细
    async getReadrecord() {
      const { memberId, readQuery } = this;
      const query = { ...readQuery, memberId };

      try {
        this.listLoading.read = true;
        const { code, data, msg } = await getReadrecordApi(query);
        this.listLoading.read = false;
        if (code == 200) {
          this.listData.read = data.list || [];
          this.total.read = Number(data.count) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading.read = false;
      }
    },

    // 获取全部城市 点击搜索时触发
    async getCity() {
      try {
        const { code, data } = await getAllCityApi();
        if (code == 200) {
          this.cityList = data || [];
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    // 获取全部事件
    async getAllEvent() {
      try {
        const { code, data } = await getApiTypeListApi();
        if (code == 200) {
          this.actionOption = data;
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    searchCoin() {
      const { memberId, datePicker1: datePicker } = this;
      const beginTime = (datePicker && datePicker[0]) || null;
      const endTime = (datePicker && datePicker[1]) || null;
      this.getRiskInfoCoin({ memberId, beginTime, endTime });
      this.coinDetail.index = 1;
      this.getRiskCoinDetail();
    },

    // 风控信息金币
    async getRiskInfoCoin(query) {
      try {
        const { code, data, msg } = await getRiskInfoCoinApi(query);
        if (code == 200) {
          const { dailyList, comboList } = data || {};
          this.formatDataForEchart(
            dailyList,
            comboList,
            'one',
            'one-all',
            'totalCoin'
          );
        } else {
          this.$message.warning(msg);
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    async getRiskCoinDetail() {
      const { index, size } = this.coinDetail;
      const { memberId, datePicker1: datePicker } = this;
      const beginTime = (datePicker && datePicker[0]) || null;
      const endTime = (datePicker && datePicker[1]) || null;
      try {
        this.coinDetail.listLoading = true;
        const { code, data, msg, count } = await getRiskInfoCoinDetailApi({
          memberId,
          beginTime,
          endTime,
          index,
          size
        });
        this.coinDetail.listLoading = false;
        if (code == 200) {
          this.coinDetail.list = data || [];
          this.coinDetail.total = Number(count) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.coinDetail.listLoading = false;
      }
    },

    searchCash() {
      const { memberId, datePicker2: datePicker } = this;
      const beginTime = (datePicker && datePicker[0]) || null;
      const endTime = (datePicker && datePicker[1]) || null;
      this.cashDetail.index = 1;
      this.getRiskInfoCash({ memberId, beginTime, endTime });
      this.getRiskCashDetail();
    },

    // 风控信息零钱
    async getRiskInfoCash(query) {
      try {
        const { code, data, msg } = await getRiskInfoCashApi(query);
        if (code == 200) {
          const { dailyList, comboList } = data || {};
          this.formatDataForEchart(
            dailyList,
            comboList,
            'two',
            'two-all',
            'totalAmount'
          );
        } else {
          this.$message.warning(msg);
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    async getRiskCashDetail() {
      const { memberId, datePicker2: datePicker } = this;
      const beginTime = (datePicker && datePicker[0]) || null;
      const endTime = (datePicker && datePicker[1]) || null;
      const { index, size } = this.cashDetail;
      try {
        this.cashDetail.listLoading = true;
        const { code, data, msg, count } = await getRiskInfoCashDetailApi({
          memberId,
          beginTime,
          endTime,
          index,
          size
        });
        this.cashDetail.listLoading = false;
        if (code == 200) {
          this.cashDetail.list = data || [];
          this.cashDetail.total = Number(count) || 0;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.cashDetail.listLoading = false;
      }
    },

    // 风控信息邀请好友
    async getChildReport() {
      try {
        const { memberId, datePicker3: datePicker } = this;
        const beginTime = (datePicker && datePicker[0]) || null;
        const endTime = (datePicker && datePicker[1]) || null;
        this.getChildList({
          beginTime: beginTime ? `${beginTime} 00:00:00` : null,
          endTime: endTime ? `${endTime} 00:00:00` : null,
          index: 1,
          size: 10000,
          sortBy: 8,
          orderBy: 'desc',
          masterId: memberId,
          childLevel: 1
        });

        const { code, data, msg } = await getChildReportApi({
          memberId,
          beginTime,
          endTime
        });
        if (code == 200) {
          const { acquisitionList, cashList, childList } = data || {};
          this.formatDataForEchart(
            null,
            null,
            'three',
            null,
            null,
            true,
            acquisitionList,
            cashList,
            childList
          );
        } else {
          this.$message.warning(msg);
        }
        // eslint-disable-next-line no-empty
      } catch (e) {}
    },

    formatDataForEchart(
      dailyList,
      comboList,
      dom1,
      dom2,
      keyName,
      isInVite,
      acquisitionList,
      cashList,
      childList
    ) {
      const date = [];
      const nameMap = {};
      const first = dailyList && dailyList[0];
      const date2 = [];
      let series = [];
      let series2 = [];
      let legend = [];

      if (isInVite) {
        const arr1 = [];
        const arr2 = [];
        const arr3 = [];

        legend = ['手机预留成功数', '邀请好友金币奖励', '邀请成功数'];
        acquisitionList.forEach((item, index) => {
          date.push(item.date);
          arr1.push(item.count);
          arr2.push(cashList[index].coin);
          arr3.push(childList[index].count);
        });

        series = [
          {
            data: arr1,
            name: '手机预留成功数',
            type: 'line'
          },
          {
            data: arr2,
            name: '邀请好友金币奖励',
            type: 'line'
          },
          {
            data: arr3,
            name: '邀请成功数',
            type: 'line'
          }
        ];

        this.upDateEchart(dom1, legend, series, date);
      } else {
        // 获取legend
        Object.keys(first).forEach(item => {
          if (item != 'dt') {
            nameMap[item] = {
              legend: first[item].typeName,
              data: []
            };
            legend.push(first[item].typeName);
          }
        });

        // 获取date
        dailyList.forEach(item => {
          date.push(item.dt);

          Object.keys(item).forEach(key => {
            if (key != 'dt') {
              nameMap[key].data.push(item[key][keyName]);
            }
          });
        });

        // 获取series
        Object.keys(nameMap).forEach(key => {
          const { legend: name, data } = nameMap[key];
          const item = {
            data,
            name,
            type: 'line'
          };
          series.push(item);
        });

        if (comboList && comboList.length > 0) {
          const data2 = [];
          comboList.forEach(item => {
            const { typeName, [keyName]: totalCoin } = item;
            date2.push(typeName);
            data2.push(totalCoin);
          });
          series2 = [
            {
              data: data2,
              type: 'bar'
            }
          ];
        }

        this.$nextTick(() => {
          this.upDateEchart(dom1, legend, series, date);
          this.upDateEchart(dom2, null, series2, date2, 20);
        });
      }
    },

    upDateEchart(dom, legend, series, date, rotate = 0) {
      const myChart = echarts.init(document.getElementById(dom));
      myChart.showLoading();
      const option = {
        color: this.$store.state.app.eChartColor,
        title: {
          show: !series || series.length == 0,
          textStyle: {
            color: '#909399',
            fontSize: 14,
            fontWeight: 400
          },
          text: '暂无数据',
          left: 'center',
          top: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: legend
        },
        grid: {
          top: 100,
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            axisLabel: { rotate },
            data: date
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    // 徒弟会员列表
    async getChildList(query) {
      try {
        this.listLoading.child = true;
        const { code, data, msg } = await getMemberList(query);
        this.listLoading.child = false;
        if (code == 200) {
          this.listData.child = data || [];
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.listLoading.child = false;
      }
    },

    // 会员状态变更历史
    async checkHistory() {
      try {
        const { memberId } = this;
        const { code, data, msg } = await getChangeRecordsApi({ memberId });
        if (code == 200) {
          this.historyData = this.formatRule(
            JSON.parse(JSON.stringify(data || []))
          );
          this.show.history = true;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.$message.warning(this.$t('there_was_an_error_in_the_request'));
      }
    },

    // 事件匹配
    querySearch(queryString, cb) {
      const restaurants = this.actionOption.map(item => ({
        value: item.apiType
      }));
      const results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      cb(results);
    },

    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },

    search(index, queryName, beginTimeName) {
      const eventMap = {
        4: this.getVisitLog,
        5: this.getActionList,
        6: this.getReadrecord
      };

      const datePicker = this[`datePicker${index}`] || [];
      const startTime = (datePicker && datePicker[0]) || null;
      const endTime = (datePicker && datePicker[1]) || null;
      this[queryName] = beginTimeName
        ? { ...this[queryName], beginTime: startTime, endTime, page: 1 }
        : { ...this[queryName], startTime, endTime, page: 1 };
      eventMap[index]();
    },

    handlePageChange(val, name, index, queryName) {
      const eventMap = {
        4: this.getVisitLog,
        5: this.getActionList,
        6: this.getReadrecord,
        7: this.getRiskCoinDetail,
        8: this.getRiskCashDetail
      };
      this[queryName][name] = val;
      eventMap[index]();
    },

    changeTime(time, index) {
      this[`active${index}`] = time;
      if (time == 'register') {
        const start = format(new Date(this.form.registerTime), 'yyyy-MM-dd');
        const end = format(new Date(), 'yyyy-MM-dd');
        this[`datePicker${index}`] = [start, end];
        return;
      }

      this[`datePicker${index}`] = timeMap[time];
    },

    // 显示全部提现账号
    showWithdrawAccount() {
      this.show.withdrawAccount = true;
      this.accountList = this.form.accountList || [];
    },

    // 跳会员列表
    goUserDetail(query) {
      const url = `${process.env.DATA_ADMIN}/#/userExceptionFiltering/memberQuery${query}`;
      window.open(url);
    },

    // 规则格式化
    formatRule(data) {
      const rule = data.map(item => {
        item.firstRuleGroupName = '';
        item.allRules = '';
        const rule = item.ruleGroupNameList;
        rule.forEach((ruleItem, index) => {
          if (
            !ruleItem.frequency
            && !ruleItem.operator
            && !ruleItem.periodOfTime
          ) {
            if (index == 0) {
              item.firstRuleGroupName = ruleItem.ruleName;
            } else {
              ruleItem.ruleName += ';';
            }
            item.allRules += ruleItem.ruleName;
          } else {
            let all = '';
            if (ruleItem.operator == '') {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${ruleItem.frequency}`;
            } else {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${ruleItem.frequency}${ruleItem.operator}${ruleItem.value}`;
            }

            if (index == 0) {
              item.firstRuleGroupName = all;
            }
            item.allRules += `${all} ; `;
          }
        });
        return item;
      });
      return rule;
    },

    toExport() {
      const xhh = new XMLHttpRequest();
      xhh.open(
        'post',
        `${process.env.BASE_API}/v1/analysis/mission/readrecordExport`
      );
      xhh.setRequestHeader('X-Token', getToken());
      xhh.setRequestHeader('content-type', 'application/json;charset=UTF-8');
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function () {
        if (xhh.readyState === 4 && xhh.status === 200) {
          const blob = new Blob([xhh.response]);
          const csvUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          let fileName = xhh
            .getResponseHeader('Content-Disposition')
            .split(';')[1]
            .split('fileName=')[1];
          const fileNameUnicode = xhh
            .getResponseHeader('Content-Disposition')
            .split('fileName*=')[1];
          if (fileNameUnicode) {
            fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
          }

          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
        }
      };
      const { memberId } = this;
      const query = { ...this.readQuery, memberId, page: 1, size: 100000 };
      xhh.send(JSON.stringify(query));
    }
  }
};
</script>

<style  lang="scss" scoped>
.info-img {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .portrait {
    width: 105px;
    height: 105px;
    object-fit: cover;
    border-radius: 50%;
  }
}

.info-num-item {
  margin-left: 30px;
  display: flex;
  flex-direction: column;

  p {
    font-size: 24px;
    text-align: center;
    line-height: 1.5;
  }

  .title {
    font-size: 16px;
    line-height: 32px;
  }
}

.info-detail {
  padding-top: 30px;
  display: flex;
  justify-content: space-between;

  p {
    font-size: 16px;
    line-height: 40px;
  }
}

.cross-line {
  border-left: 1px solid #ddd;
}

.label {
  display: inline-block;
  width: 260px;
}

.pointer {
  cursor: pointer;
}

.disabled {
  pointer-events: none;
  cursor: default;
}

.flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding-top: 30px;
}

.echart {
  width: 50%;
  height: 520px;
}

.table {
  margin-bottom: 15px;
  width: 50%;
  max-height: 520px;
}

.blue {
  color: rgb(22, 155, 213);
}

.m-r-100 {
  margin-right: 100px;
}

.risk {
  width: 50%;
  display: flex;
  justify-content: space-between;

  .risk-item {
    display: flex;
    flex-direction: column;
    justify-content: center;

    p {
      font-size: 24px;
      text-align: center;
      line-height: 1.5;
    }

    .title {
      font-size: 16px;
      line-height: 32px;
    }
  }
}

.account {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  line-height: 40px;
}

.green {
  color: #02830f;
}

.red {
  color: #d9001b;
}

.black {
  color: #000000;
}

.block {
  text-align: right;
  padding-top: 5px;
}
</style>
